<?php

!defined('IN_NOVA') && exit('Access Denied!');

class Attachement {

	public function start() {
		$fileid = getGP('id','G','int');
		$view = getGP('view','G');

		if( !$fileid ) {
			@header('content-type: text/html; charset=utf-8');
			exit('缺少参数！');
		}

		//防盗链
		if( !isset( $_SERVER['HTTP_REFERER'] ) ) access_denied();

		$allow_host = $_CACHE['set'][0]['domain'];
		$referer = parse_url($_SERVER['HTTP_REFERER']);

		if ( 'http://' . $referer['host'] . '/' != $allow_host ) {
			access_denied();
		}


		$file = $db->fetch_one_array("SELECT ul_id,ul_filepath,ul_filetype,ul_fileext,ul_filesize,ul_thumb,ul_time FROM `" . PREFIX_STR . "upload` WHERE ul_id = $fileid");

		if( !isset( $file['ul_filepath'] ) ) {
			@header('content-type: text/html; charset=utf-8');
			exit('文件未找到，可能已经被管理员删除！');
		}

		$file['ul_filepath'] = XKLOG_ROOT . $file['ul_filepath'];

		if ( !$file ) {
			access_denied();
		} else {
			//通过判断getimagesize取出的图片信息是否存在类型标记和色彩位深来防止伪造。
			$isimage = false;
			if ( stristr( $file['ul_filetype'], 'image' ) ) {
				$imginfo = @getimagesize( $file['ul_filepath'] );
				if ( $imginfo[2] && $imginfo['bits'] ) {
					$isimage = true;
				}
				unset( $imginfo );
			}
			// 附件读取形式，inline直接读取，attachment下载到本地
			$disposition = $isimage ? 'inline' : 'attachment';
			// 统计附件下载次数
			if ( $disposition == 'attachment' ) {
				$db->query("UPDATE `" . PREFIX_STR . "upload` SET ul_downloads = ul_downloads + 1 WHERE ul_id = $fileid");
			} elseif ( $view == 'thumb' && !empty( $file['ul_thumb'] ) ) {
				$file['ul_filepath'] = $file['ul_thumb'];
			}
			$file['ul_filetype'] = $file['ul_filetype'] ? $file['ul_filetype'] : 'application/octet-stream';
			$file_name = basename( get_date( 'YmdHis',PHP_TIME ) . mt_rand(10,99) . '.' . $file['ul_fileext'] );
			if ( is_readable( $file['ul_filepath'] ) ) {
				ob_end_clean();
				header( 'Cache-control: max-age=31536000' );
				header( 'Expires: ' . get_date('D, d M Y H:i:s',PHP_TIME + 31536000) . ' GMT' );
				header( 'Last-Modified: ' . get_date('D, d M Y H:i:s',$file['ul_time']) . ' GMT' );
				header( 'content-Encoding: none' );
				header( 'content-type: ' . $file['ul_filetype'] );
				header( 'content-Disposition: ' . $disposition . '; filename=' . urlencode( $file_name ) );
				header( 'content-Length: ' . $file['ul_filesize'] );
				$fp = fopen( $file['ul_filepath'], 'rb' ); 
				fpassthru($fp);
				fclose($fp);
				exit;		
			} else {
				@header('content-type: text/html; charset=utf-8');
				exit('文件读取失败！');
			}
		}
	}

	private function access_denied() {
		header('content-Encoding: none');
		header('content-type: image/gif');
		header('content-Disposition: inline; filename="open_denied.gif"');
		$fp = fopen('../images/open_denied.gif','rb');
		fpassthru($fp);
		fclose($fp);
		exit();
	}

}
?>
